package fr.poy.mygluco.client.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreSorter;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.Time;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import fr.poy.mygluco.client.App;
import fr.poy.mygluco.client.gxt.AppListener;
import fr.poy.mygluco.model.Record;

public class LogBook extends ContentPanel implements AppListener{

	PagingLoader<PagingLoadResult<ModelData>> loader;
	FormBinding formBindings;
	ListStore<BeanModel> store;

	public LogBook() { 
		BorderLayout bl =new BorderLayout();
		this.setLayout(bl);
		this.setHeaderVisible(false);
		this.setTopComponent(getToolbar());
		// proxy and reader
		RpcProxy<PagingLoadResult<Record>> proxy = new RpcProxy<PagingLoadResult<Record>>() {
			@Override
			public void load(Object loadConfig, AsyncCallback<PagingLoadResult<Record>> callback) {
				App.getService().listRecord((PagingLoadConfig) loadConfig, callback);
			}
		};
		// loader and store
		loader = new BasePagingLoader<PagingLoadResult<ModelData>>(proxy, new BeanModelReader());
		store = new ListStore<BeanModel>(loader);
		loader.setRemoteSort(true);
		loader.load();
		final PagingToolBar toolBar = new PagingToolBar(130);
		toolBar.bind(loader);

		// column model
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();

		ColumnConfig cc = new ColumnConfig("day", App.getMessages().recordLabelJour(), 50); 
		cc.setRenderer(new GridCellRenderer<ModelData>() {
			public Object render(ModelData model, String property, com.extjs.gxt.ui.client.widget.grid.ColumnData config
					, int rowIndex, int colIndex,ListStore<ModelData> store, Grid<ModelData> grid) {
				return DateTimeFormat.getFormat(App.getUserProfile().getDayFormat())
				.format(((Date) model.get("date")));
			}
		});
		columns.add(cc);

		cc = new ColumnConfig("date", App.getMessages().recordLabelDate(), 70);
		cc.setDateTimeFormat(DateTimeFormat.getFormat(App.getUserProfile().getDateFormat()));
		columns.add(cc);

		cc = new ColumnConfig("gxtTime", App.getMessages().recordLabelTime(), 55);
		cc.setRenderer(new GridCellRenderer<ModelData>() {
			public Object render(ModelData model, String property, com.extjs.gxt.ui.client.widget.grid.ColumnData config
					, int rowIndex, int colIndex,ListStore<ModelData> store, Grid<ModelData> grid) {
				return DateTimeFormat.getFormat(App.getUserProfile().getTimeFormat())
				.format(((Time) model.get(property)).getDate());
			}
		});
		columns.add(cc);

		cc = new ColumnConfig("bg", App.getMessages().recordLabelBg() + " "+ App.getUserProfile().getBgUnit(), 50);
		cc.setAlignment(HorizontalAlignment.RIGHT);

		GridCellRenderer<ModelData> colorRenderer = new GridCellRenderer<ModelData>() {
			public String render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {
				Integer val = (Integer) model.get(property);
				String style = 
					val < App.getUserProfile().getLimitHypo() ? "red" :
						val < App.getUserProfile().getBgLow() ? "orange" :
							val < App.getUserProfile().getBgHigh() ? "green" : 
								"blue"; 
				return "<span style='color:" + style + "'>" + val + "</span>";
			}
		};
		cc.setRenderer(colorRenderer);
		columns.add(cc);

		cc = new ColumnConfig("flag", App.getMessages().recordLabelFlag(), 30);
		cc.setAlignment(HorizontalAlignment.CENTER);  
		columns.add(cc);
		
		cc = new ColumnConfig("ins1", App.getMessages().recordLabelIns1() , 50);
		cc.setAlignment(HorizontalAlignment.RIGHT);
		columns.add(cc);
		
		cc = new ColumnConfig("ins2", App.getMessages().recordLabelIns2() , 50);
		cc.setAlignment(HorizontalAlignment.RIGHT);
		columns.add(cc);
		
		cc = new ColumnConfig("ins3", App.getMessages().recordLabelIns3() , 50);
		cc.setAlignment(HorizontalAlignment.RIGHT);
		columns.add(cc);
		
//		cc = new ColumnConfig("source", App.getMessages().recordLabelSource(), 20);
//		cc.setAlignment(HorizontalAlignment.CENTER);  
//		//final AbstractImagePrototype s = IconHelper.createPath(GWT.getModuleBaseURL() + "images/bang.gif" );
//		cc.setRenderer(
//		new GridCellRenderer<ModelData>() { 
//			public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {
//				if(model.get(property).equals(Record.SOURCE.METER))
//					return "";
//				return "<img src=\"images/bang.gif\" />";
//			} 
//			}); 
//        columns.add(cc);
		
		columns.add(new ColumnConfig("event", App.getMessages().recordLabelEvent(), 150));
		columns.add(new ColumnConfig("comment",App.getMessages().recordLabelComment(), 300));
		ColumnModel cm = new ColumnModel(columns);

		final Grid<BeanModel> grid = new Grid<BeanModel>(store, cm);
		grid.setLoadMask(true);
		grid.setBorders(true);
		grid.setAutoExpandColumn("comment");
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			public void handleEvent(GridEvent<BeanModel> be) {
				loader.load();
			}
		});
		grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
		grid.getSelectionModel().addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<ModelData>>() {
			public void handleEvent(SelectionChangedEvent<ModelData> be) {
				if (be.getSelection().size() > 0) {
					formBindings.bind((ModelData) be.getSelection().get(0));
				} else {
					formBindings.unbind();
				}
			}
		});

		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		this.add(grid, centerData);

		// ------------------------------
		// WEST
		FormPanel west = new FormPanel();  
		west.setIconStyle("toolbar-editGrid");
		west.setHeading("Saisie");
		west.setLayout(new FitLayout()); 
		//------------------
		DateField date = new DateField();
		date.setName("date");
		date.setFieldLabel(App.getMessages().recordLabelDate());
		date.getPropertyEditor().setFormat(DateTimeFormat.getFormat(App.getUserProfile().getDateFormat()));
		west.add(date);
		
		
		formBindings = new FormBinding(west, true);   
		//-----------------------
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.EAST, 200, 200, 200);
		westData.setCollapsible(true);
		westData.setMargins(new Margins(0, 0, 0, 5));
		this.add(west, westData); 
		// south
		BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 30);
		this.add(toolBar, southData);

	}

	@Override
	public void onRecordListChange() { 
		loader.load();
	}
	
	private ToolBar getToolbar(){
		ToolBar tb = new ToolBar();   
		
		Button t = new Button(App.getMessages().buttonRefresh(), IconHelper.createStyle("toolbar-refresh"));   
		t.addSelectionListener( new SelectionListener<ButtonEvent>(){  
			public void componentSelected(ButtonEvent ce) { 
				store.getLoader().load();
			} 
		});
		tb.add(t); 
		
		t = new Button(App.getMessages().fileXLS(), IconHelper.createStyle("file-extension-xls"));   
		t.addSelectionListener( new SelectionListener<ButtonEvent>(){  
			public void componentSelected(ButtonEvent ce) { 
				//TODO window : parametrage mois
				Window.Location.assign(   
						GWT.getModuleBaseURL() +"download?type=logBookXls"
						//+"&session="+sessionId 
						); 
			}
		});
		tb.add(t);  
		tb.add(new SeparatorToolItem());
		 
		return tb;
	}

}
